﻿using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Common;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace lwzlz.Application.System
{
    /// <summary>
    /// 
    /// </summary>
    public class MenuService
    {
        private readonly IRepository<Menu> _repository;

        /// <summary>
        /// 
        /// </summary>
        public MenuService()
        {
            _repository = new Repository<Menu>();
        }

        #region 菜单

        #region 获取菜单

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public MenuOutput GetMenu(int id)
        {
            var entity = _repository.Get(id);
            return Mapper.Map<MenuOutput>(entity);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Menu GetMenuModel(int id)
        {
            return _repository.Get(id);
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<MenuOutput> GetMenuList(object whereConditions)
        {
            var list = _repository.GetList(whereConditions).ToList();

            var menuList = new List<Menu>();
            GetChild(0, list, ref menuList);

            var config = new MapperConfiguration(p => p.CreateMap<Menu, MenuOutput>().ForMember(
                dest => dest.MenuName, opt => opt.MapFrom(
                    src => ZString.ReplicateString("　　", src.MenuDeep ?? 0) + "|—" + src.MenuName)));
            var mapper = config.CreateMapper();

            return mapper.Map<IEnumerable<MenuOutput>>(menuList);
        }

        /// <summary>
        /// 获取子菜单
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="allList"></param>
        /// <param name="codeList"></param>
        protected void GetChild(int parentId, List<Menu> allList, ref List<Menu> codeList)
        {
            var list = allList.FindAll(p => p.ParentId == parentId).OrderBy(p => p.SortIndex).ToList();
            if (list.LongCount() > 0)
            {
                foreach (Menu item in list)
                {
                    codeList.Add(item);
                    GetChild(item.Id, allList, ref codeList);
                }
            }
        }

        #endregion

        #region 编辑菜单

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <remarks></remarks>
        public int? AddMenu(MenuInput model)
        {
            var entity = Mapper.Map<Menu>(model);
            entity.MenuUrl = SpliceUrl(model);
            entity.MenuType = 1;
            entity.IsDeleted = false;
            entity.CreationTime = DateTime.Now;
            entity.CreatorUserID = UserAuthentication.GetCurrentUser().UserID;

            return _repository.Insert(entity);
        }

        /// <summary>
        /// 修改菜单
        /// </summary>
        public int EidtMenu(MenuInput model)
        {
            var entity = _repository.Get(model.Id);

            Mapper.Map(model, entity);
            entity.MenuUrl = SpliceUrl(model);
            entity.LastModificationTime = DateTime.Now;
            entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;

            return _repository.Update(entity);
        }

        /// <summary>
        /// 拼接URL
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        protected string SpliceUrl(MenuInput model)
        {
            StringBuilder strbUrl = new StringBuilder();
            if (!string.IsNullOrEmpty(model.MenuArea))
            {
                strbUrl.Append("/" + model.MenuArea);
            }
            if (!string.IsNullOrEmpty(model.MenuControl))
            {
                strbUrl.Append("/" + model.MenuControl);
                if (!string.IsNullOrEmpty(model.MenuAction))
                {
                    strbUrl.Append("/" + model.MenuAction);
                    if (!string.IsNullOrWhiteSpace(model.MenuParam))
                    {
                        strbUrl.Append("/" + model.MenuParam);
                    }
                }
            }
            return strbUrl.ToString();
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public int Update(int id, string field, string value)
        {
            var entity = _repository.Get(id);
            // 获取菜单类公共属性
            PropertyInfo[] props = entity.GetType().GetProperties();
            bool isHasField = false; // 是否含有此字段
            foreach (var prop in props)
            {
                if (field == prop.Name)
                {
                    isHasField = true;

                    var type = prop.PropertyType;
                    var val = prop.GetValue(entity);

                    prop.SetValue(entity, Convert.ChangeType(value, type));
                }
            }
            if (!isHasField)
            {

            }
            return _repository.Update(entity);
        }

        #endregion

        #endregion

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(int id)
        {
            return _repository.Delete(id);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateIsEnable(Menu model)
        {
            return _repository.Update(model);
        }
    }
}
